package com.example.famhealing.init;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import com.example.famhealing.Font;
import com.example.famhealing.R;
import com.example.famhealing.R.drawable;
import com.example.famhealing.R.id;
import com.example.famhealing.R.layout;
import com.example.famhealing.schedule.FunctionActivity;
import com.example.famhealing.HangulUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class FamComposition1 extends Font implements Serializable {
	
		public static ArrayList<ListItemVO> contactsContractList = new ArrayList<ListItemVO>();
		private String searchKeyword;
		private MyAsyncTask myAsyncTask;
		ListView myList;
		//////////
		private int flg = 0;
		private int pos;
		private String member;
		private ImageView me;
		private String who = null;
//		private int invite_phone_no;
		private String invite_phone_no;
		private int invite_pos;

		private ArrayList<String> pn_list = new ArrayList<String>();
		private ArrayList<Integer> al = new ArrayList<Integer>();
		final static String ACTION_SENT = "ACTION_MESSAGE_SENT";
		final static String ACTION_DELIVERY = "ACTION_MESSAGE_DELIVERY";

		ImageView fa, mo, gf, gm, ob, os, yb, ys, ma, wo, so, da, hu, wi;
		ImageView mgf, mgm, hf, hm, so2, so3, so4, da4, da2, da3, dh, sw;
		ArrayList<ImageView> fam = new ArrayList<ImageView>();
		LinearLayout linearlayout;
		LinearLayout famCom;
		LinearLayout phoneList;
		LinearLayout add;
		RadioButton btn;
		Button finishbtn;


		public void onCreate(Bundle savedInstanceState) 
		{
			super.onCreate(savedInstanceState);
			setContentView(R.layout.fam_composition_layoutver);  
			Intent intent = getIntent();
			pos = intent.getIntExtra("position", 0);
			member = intent.getStringExtra("member");
			flg = intent.getIntExtra("flg", 0);

			finishbtn = (Button)findViewById(R.id.finishbtn);
			finishbtn.setVisibility(View.GONE);

			fa = (ImageView)findViewById(R.id.fa);
			mo = (ImageView)findViewById(R.id.mo);
			gf = (ImageView)findViewById(R.id.gf);
			gm = (ImageView)findViewById(R.id.gm);
			ob = (ImageView)findViewById(R.id.ob);
			os = (ImageView)findViewById(R.id.os);
			yb = (ImageView)findViewById(R.id.yb);
			ys = (ImageView)findViewById(R.id.ys);
			ma = (ImageView)findViewById(R.id.ma);
			wo = (ImageView)findViewById(R.id.wo);
			so = (ImageView)findViewById(R.id.so);
			da = (ImageView)findViewById(R.id.da);
			hu = (ImageView)findViewById(R.id.hu);
			wi = (ImageView)findViewById(R.id.wi);

			//	mgm = (ImageView)findViewById(R.id.mgm);
			//	mgf = (ImageView)findViewById(R.id.mgf);
			//	hf = (ImageView)findViewById(R.id.hf);
			//	hm = (ImageView)findViewById(R.id.hm);
			//	so2 = (ImageView)findViewById(R.id.so2);
			//	so3 = (ImageView)findViewById(R.id.so3);
			//	so4 = (ImageView)findViewById(R.id.so4);
			//	da2 = (ImageView)findViewById(R.id.da2);
			//	da3 = (ImageView)findViewById(R.id.da3);
			//	da4 = (ImageView)findViewById(R.id.da4);

			LinearLayout li = (LinearLayout)findViewById(R.id.linear);
			LinearLayout l2 = (LinearLayout)findViewById(R.id.linear2);
			LinearLayout l3 = (LinearLayout)findViewById(R.id.linear3);
			//	linearlayout = (LinearLayout)findViewById(R.id.LinearLayout);
			famCom = (LinearLayout)findViewById(R.id.famcomposition);
			phoneList = (LinearLayout)findViewById(R.id.phonelist);

			myAsyncTask = new MyAsyncTask();
	        myAsyncTask.execute();
	        
			Button button = (Button)findViewById(R.id.button1);
			EditText t = (EditText)findViewById(R.id.edit1);
			t.addTextChangedListener(textWatcherInput); 
			try {
//				displayList();
		        myAsyncTask.execute();
				
			} catch (Exception e) {
				Log.e("sine", e.getMessage(), e);
				e.printStackTrace();
			}

			if (pos == 0) {
				fam.add(fa);
				fam.add(mo);
				fam.add(so);
				fam.add(da);
				for (int i = 0; i < fam.size(); i++) {

				}
				//		li.setVisibility(1);
				fa.setVisibility(0);
				mo.setVisibility(0);
				so.setVisibility(0);
				da.setVisibility(0);		

			} else if (pos == 1) {
				hu.setVisibility(0);
				wi.setVisibility(0);
			} else if (pos == 2) {
				ob.setVisibility(0);
				os.setVisibility(0);
				ma.setVisibility(0);
				yb.setVisibility(0);
				ys.setVisibility(0);
			} else if (pos == 3) {
				gf.setVisibility(0);
				gm.setVisibility(0);
				fa.setVisibility(0);
				mo.setVisibility(0);
				so.setVisibility(0);
				da.setVisibility(0);
			} else if (pos == 4) {
				ma.setVisibility(0);
				wo.setVisibility(0);
			} else if (pos == 5) {
				ma.setVisibility(0);
			}


		}



		///////////
		public void onClick (View v) {
			Intent intent;
			searchKeyword=null;

			switch (v.getId()) {
			case R.id.backbtn:
						intent = new Intent(this, FamCompositionActivity.class);
						intent.putExtra("pos", pos);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
						finish();
				break;
			case R.id.finishbtn:
				inviteAlert(v);
				break;
			case R.id.addMember:
				add.setVisibility(v.VISIBLE);
				famCom.setVisibility(v.GONE);
				break;
			case R.id.gf:
				me = gf;
				who = "할아버지";
				if (flg == 0)
					openAlert(v);
				else {
					viewController();
					flg++;
				}
				break;
			case R.id.gm:
				me = gm;
				who = "할머니";
				if (flg == 0)
					openAlert(v);
				else {
					viewController();
					flg++;
				}
				break;
			case R.id.fa:
				me = fa;
				who = "아버지";
				if (flg == 0){
					openAlert(v);
				} else {
					viewController();
					flg++;
				}
				break;
			case R.id.mo:
				me = mo;
				who = "어머니";
				if (flg == 0){
					openAlert(v);
				}
				else {
					viewController();
					flg++;
				}
				break;
			case R.id.hu:
				me = hu;
				who = "남편";
				if (flg == 0){
					openAlert(v);
				}
				else {
					viewController();
					flg++;
				}
				break;
			case R.id.wi:
				me = wi;
				who = "아내";
				if (flg == 0){
					openAlert(v);
				}
				else {
					viewController();
					flg++;
				}
				break;
			case R.id.ob:
				me = ob;
				who = "형/오빠";
				if (flg == 0){
					openAlert(v);
				}
				else {
					viewController();
					flg++;
				}
				break;
			case R.id.os:
				me = os;
				who = "누나/언니";
				if (flg == 0){
					openAlert(v);
				}
				else {
					viewController();
					flg++;
				}
				break;
			case R.id.yb:
				me = yb;
				who = "남동생";
				if (flg == 0){
					openAlert(v);
				}
				else {
					viewController();
					flg++;
				}
				flg++;
				break;
			case R.id.ys:
				me = ys;
				who = "여동생";
				if (flg == 0){
					openAlert(v);
				}
				else {
					viewController();
					flg++;
				}
				break;
			case R.id.ma:
				me = ma;
				who = "나";
				if (flg == 0){
					openAlert(v);
				}
				else {
					viewController();
					flg++;
				}
				break;
			case R.id.wo:
				me = wo;
				who = "나";
				if (flg == 0){
					openAlert(v);
				}
				else {
					viewController();
					flg++;
				}
				break;
			case R.id.so:
				me = so;
				who = "아들";
				if (flg == 0){
					openAlert(v);
				}
				else {
					viewController();
					flg++;
				}
				break;
			case R.id.da:
				me = da;
				who = "딸";
				if (flg == 0){
					openAlert(v);
				}
				else {
					viewController();
					flg++;
				}
				break;
			}

		}

		private void viewController() {

			famCom.setVisibility(View.GONE);
			phoneList.setVisibility(View.VISIBLE);
			me.setImageDrawable(getResources().getDrawable(R.drawable.icon));

		}

		private void openAlert(View view) {
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(FamComposition1.this);
			alertDialogBuilder.setTitle("본인 위치 지정 확인");
			alertDialogBuilder.setMessage("본인을 가족 구성원 중 " + who + "(으)로 등록하시겠습니까?");
			alertDialogBuilder.setPositiveButton("확인",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					flg++;
					me.setImageDrawable(getResources().getDrawable(R.drawable.icon));       
					finishbtn.setVisibility(View.VISIBLE);
				}
			});

			alertDialogBuilder.setNegativeButton("취소",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					dialog.cancel();
				}
			});

			AlertDialog alertDialog = alertDialogBuilder.create();
			alertDialog.show();
		}

		private void inviteAlert(View view) {
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(FamComposition1.this);
			alertDialogBuilder.setTitle("가족 구성 완료 확인");
			alertDialogBuilder.setMessage("초대하시겠습니까?");
			alertDialogBuilder.setPositiveButton("확인",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					SmsManager sms = SmsManager.getDefault();

					for (int i = 0; i < pn_list.size(); i++) {
						String num = pn_list.get(i);
						String text = "초대합니다";

						if (num.length() == 0 || text.length() == 0) {
							return;
						}		

						PendingIntent SentIntent = PendingIntent.getBroadcast(
								FamComposition1.this, 0, new Intent(ACTION_SENT), 0);
						PendingIntent DeliveryIntent = PendingIntent.getBroadcast(
								FamComposition1.this, 0, new Intent(ACTION_DELIVERY), 0);
						sms.sendTextMessage(num, null, text, SentIntent, DeliveryIntent);
						
					}
					pn_list.clear();

					Intent intent = new Intent(FamComposition1.this, FunctionActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
				}
			});

			alertDialogBuilder.setNegativeButton("취소",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					dialog.cancel();
				}
			});

			AlertDialog alertDialog = alertDialogBuilder.create();
			alertDialog.show();
		}

		public void onClickFinish(View v) {

//			ArrayList<ListItemVO> phonelist = getContactsContract();
			switch (v.getId()) {
			case R.id.button_ok:

				famCom.setVisibility(v.VISIBLE);
				phoneList.setVisibility(v.GONE);
				myList.setItemChecked(invite_pos, false);
				pn_list.add(invite_phone_no);
				break;

			}
		}
		
		TextWatcher textWatcherInput = new TextWatcher() {   
			@Override  
			public void onTextChanged(CharSequence s, int start, int before, int count) {   
			}   
			@Override  
			public void beforeTextChanged(CharSequence s, int start, int count,int after) {   
			}   
			@Override              
			public void afterTextChanged(Editable s) {  
				
				searchKeyword=s.toString();
				try {
//					displayList();
			        myAsyncTask.execute();
				} catch (Exception e) {
					Log.e("sine", e.getMessage(), e);
					e.printStackTrace();
				}
				
			}
		};    
		
		private void addSearchResult(ArrayList<ListItemVO> contactsContractList, String item1,String item2,String item3) throws Exception {
			if (contactsContractList == null) {
				throw new NullPointerException("contactsContractList null 입니다.");
			}
			if (searchKeyword != null && "".equals(searchKeyword.trim()) == false) {
				String iniName = HangulUtils.getHangulInitialSound(item1,searchKeyword);
				if (iniName.indexOf(searchKeyword) >= 0||nvlString(item1).indexOf(searchKeyword)!=-1||nvlString(item2).indexOf(searchKeyword)!=-1) {
					contactsContractList.add(new ListItemVO(item1, item2, item3));
				}
			} else {
				contactsContractList.add(new ListItemVO(item1, item2, item3));
			}
		}
		
		public class MyAsyncTask extends AsyncTask<Void, String, ArrayList<ListItemVO>> {
			 
	        @Override
	        protected void onPreExecute() {
	            super.onPreExecute();
	        }
	         
	        @Override
	        protected ArrayList<ListItemVO> doInBackground(Void...voids) {
	        	String [] arrProjection = { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };
				String [] arrPhoneProjection = { ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.TYPE };
				Cursor clsCursor = getContentResolver().query( ContactsContract.Contacts.CONTENT_URI, arrProjection, ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1" , null, null );
				contactsContractList.clear();
				while( clsCursor.moveToNext() )
				{
					String strContactId = clsCursor.getString( 0 );
					String item2=null;
					String item3=null;
					Cursor clsPhoneCursor = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, arrPhoneProjection
							, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + strContactId, null, null );
					while( clsPhoneCursor.moveToNext() )
					{
						switch(Integer.parseInt(clsPhoneCursor.getString( 1 ))){
						case 1: item3=clsPhoneCursor.getString(0);break;
						case 2: item2=clsPhoneCursor.getString(0);break;
						default : item3=clsPhoneCursor.getString(0);break;
						}
					}
					try {
						addSearchResult(contactsContractList,clsCursor.getString(1),item2,item3);
					} catch (Exception e) {
						e.printStackTrace();  
					}
					clsPhoneCursor.close();   
				}
				clsCursor.close( );
				return contactsContractList;
	        }
	         
	        @Override
	        protected void onPostExecute(ArrayList<ListItemVO> contactsContractList) {
	            super.onPostExecute(contactsContractList);
//	            ArrayList<ListItemVO> contactsContractList = null;
//				contactsContractList = getContactsContract();
				ContactsListAdapter<ListItemVO> adapter = new ContactsListAdapter<ListItemVO>(FamComposition1.this, R.layout.list, contactsContractList);
				myList = (ListView) findViewById(R.id.list);
				myList.setAdapter(adapter);
				myList.setOnItemClickListener(mItemClickListener);
				myList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	            
	             
	        }
	         
	        
	         
	    }
		
//		private void displayList() throws Exception {
//			ArrayList<ListItemVO> contactsContractList = null;
//			contactsContractList = getContactsContract();
//			ContactsListAdapter<ListItemVO> adapter = new ContactsListAdapter<ListItemVO>(
//					this, R.layout.list, contactsContractList);
//			myList = (ListView) findViewById(R.id.list);
////			myList.setAdapter(adapter);
//			myList.setOnItemClickListener(mItemClickListener);
//			myList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//			System.out.println("displayList");
//			//  setListAdapter(adapter);
//		}
		
		AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				invite_phone_no = contactsContractList.get(position).getItem2();
				invite_pos = position;
			}
		};

		private class ContactsListAdapter<ListItemVO> extends ArrayAdapter<ListItemVO> {
			private ArrayList<ListItemVO> list;
			private Context context;
			public ContactsListAdapter(Context context, int textViewResourceId,
					ArrayList<ListItemVO> items) {
				super(context, textViewResourceId, items);  
				this.context = context;  
				list = items;
			}
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View view = convertView;
				if (view == null) {
					LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = vi.inflate(R.layout.phone_list, null);
				}
				ListItemVO contacts = list.get(position);
				if (contacts != null) {
					TextView text1 = (TextView) view.findViewById(R.id.TextView01);
					TextView text2 = (TextView) view.findViewById(R.id.TextView02);
					TextView text3 = (TextView) view.findViewById(R.id.TextView03);
					text2.setVisibility(convertView.VISIBLE);
					text3.setVisibility(convertView.VISIBLE);
					text1.setText(nvlString(((com.example.famhealing.init.FamComposition1.ListItemVO) contacts).getItem1()));
					if (!nvlString(((com.example.famhealing.init.FamComposition1.ListItemVO) contacts).getItem2()).equals("")) {
						text2.setText(nvlString(((com.example.famhealing.init.FamComposition1.ListItemVO) contacts).getItem2()));
						text3.setVisibility(convertView.GONE);
					}
					else
						text2.setVisibility(convertView.GONE);
					text3.setText(nvlString(((com.example.famhealing.init.FamComposition1.ListItemVO) contacts).getItem3()));   
				} 
				
				Collections.sort(list, new NameAscCompare());
				return view;
				
			}
			
			//연락처 리스트 정렬
			public class NameAscCompare implements Comparator<ListItemVO> {
				@Override
				public int compare(ListItemVO arg0, ListItemVO arg1) {
					// TODO Auto-generated method stub
					return ((com.example.famhealing.init.FamComposition1.ListItemVO) arg0).getItem1().compareTo(((com.example.famhealing.init.FamComposition1.ListItemVO) arg1).getItem1());
				}
		 
			}
			
		}
		public class ListItemVO {
			private String item1;
			private String item2;
			private String item3;
			public ListItemVO(String item1, String item2, String item3) {
				this.item1 = item1;
				this.item2 = item2;
				this.item3 = item3;
			}
			public String getItem1() {
				return this.item1;
			}
			public String getItem2() {
				return this.item2;
			}
			public String getItem3() {
				return this.item3;
			}
		}
		public static String nvlString(String str) {
			if(str == null) return "";
			else return str.trim();
		}
	}
